<template>
  <div>
    <el-dialog title="提示" v-model="dialogVisible" width="30%">
      <span>确认要删除该条数据吗?</span>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisible = false">取 消</el-button>
          <el-button type="primary" @click="handleDelete">确 定</el-button>
        </span>
      </template>
    </el-dialog>
    <el-dialog :title="title" v-model="showDialog" width="450px">
      <div>
        <QrCodeGenerator :value="qrUrl" size="400" level="H"></QrCodeGenerator>
      </div>
      <template #footer>
        <span class="dialog-footer">
          <el-button type="primary" @click="closeDialog">确 定</el-button>
        </span>
      </template>
    </el-dialog>

    <el-dialog title="导入商家数据" v-model="importVisible" width="450px">
      <div>
        <el-upload
            action=""
            :before-upload="handleBeforeUpload"
            :on-change="handleChange"
            :show-file-list="false">
          <el-button type="primary">点击上传Excel文件</el-button>
        </el-upload>
      </div>
      <template #footer>
        <span class="dialog-footer">
          <el-button type="primary" @click="closeImportDialog">确 定</el-button>
        </span>
      </template>
    </el-dialog>


    <el-dialog title="商家会员卡配置" v-model="configDialogVisible" width="40%">
      <div>

        <el-table :data="configData" style="width: 100%;font-size: 12px;">
          <el-table-column label="商家" prop="storeName" width="200">
          </el-table-column>
          <el-table-column label="会员卡名称" prop="vipCardTemplateName" width="100">
          </el-table-column>
          <el-table-column label="优惠金额">
            <template #default="scope">
              <el-input v-model="scope.row.singleDiscount" name="tel">
              </el-input>
            </template>
          </el-table-column>
          <el-table-column width="100" align="center" fixed="right" label="操作">
            <template #default="scope">
              <el-button text size="small" class="operation_bt" :icon="Edit" type="primary"
                         @click="saveConfig(scope.row)">
                保存
              </el-button>
            </template>
          </el-table-column>
        </el-table>

      </div>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="configDialogVisible = false">取 消</el-button>
          <el-button type="primary" @click="batchSave">确 定</el-button>
        </span>
      </template>
    </el-dialog>

    <div class="search">
      <el-form label-width="80px">
        <el-row>
          <el-col :span="6" style="padding: 0 8px;">
            <el-form-item label="商家名称">
              <el-input v-model="searchObject.name" placeholder="商家名称" name="name">
              </el-input>
            </el-form-item>
          </el-col>
          <el-col :span="6" style="padding: 0 8px;">
            <el-form-item label="联系电话">
              <el-input v-model="searchObject.phone" placeholder="联系电话" name="phone">
              </el-input>
            </el-form-item>
          </el-col>

          <el-col :span="12" style="padding: 0 10px;margin-top: 5px;">
            <el-row type="flex" justify="end">
              <el-button type="primary" @click="search">搜索</el-button>
              <el-button plain @click="clearSearch">清除条件</el-button>
            </el-row>
          </el-col>
        </el-row>
      </el-form>
    </div>
    <div class="data-content">
      <div class="tool-add">
        <el-button type="primary" @click="addView">新增</el-button>
        <el-button type="primary" @click="exportToExcel2">导出Excel</el-button>
        <el-button type="primary" @click="importToExcel">导入Excel</el-button>

      </div>

      <el-table v-loading="loading" :data="pageData.data" @sort-change="changeTableSort"
                style="width: 100%;font-size: 12px;">
        <el-table-column label="商家名称" prop="name"
                         width="200">
        </el-table-column>
        <el-table-column label="商家分类" prop="storeCatalogName" width="100">
        </el-table-column>
        <el-table-column label="联系电话" prop="phone" width="120">
        </el-table-column>
        <el-table-column label="商家收入" prop="accountAmount" sortable="custom" width="100">
        </el-table-column>
        <el-table-column label="是否上线" prop="storeStatus" width="100" :formatter="showState">
        </el-table-column>
        <el-table-column label="创建时间" prop="addDate">
        </el-table-column>
        <el-table-column width="360" align="center" fixed="right" label="操作">
          <template #default="scope">
            <el-switch v-model="scope.row.storeStatus" active-value="normal" inactive-value="disable"
                       active-text="已上线"
                       inactive-text="已下线"
                       inline-prompt
                       @change="updateShopState(scope.row)"/>
            <el-button text size="small" class="operation_bt" :icon="InfoFilled" type="info"
                       @click="showPayView(scope.row)">付款码
            </el-button>
            <el-button text size="small" class="operation_bt" :icon="InfoFilled" type="info"
                       @click="showView(scope.row)">详情
            </el-button>

            <el-button text size="small" class="operation_bt" :icon="Edit" type="primary"
                       @click="editView(scope.row)">
              编辑
            </el-button>

            <el-button text :icon="Delete" class="operation_bt" type="danger" size="small"
                       style="cursor: pointer;"
                       @click="deleteData(scope.row)">删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <div class="page">
        <el-pagination background :current-page="searchObject.no" :page-sizes="[10, 20, 30,50, 100]"
                       :page-size="pageData.size" :pager-count="5"
                       layout="total, sizes, prev, pager, next, jumper" :page-count="pageData.totalPage"
                       :total="pageData.total" @size-change="sizeChange" @current-change="pageChange">
        </el-pagination>
      </div>
    </div>
  </div>
</template>

<script setup>
import {Delete, Edit, InfoFilled} from '@element-plus/icons-vue'
import {defineStore} from 'pinia'
import {usePage} from "@/utils/usePage";
import {useDelete} from "@/utils/useDelete";
import {useView} from "@/utils/useView";
import http from "@/utils/request";
import * as XLSX from 'xlsx';
import ExcelJS from 'exceljs';
import {saveAs} from 'file-saver';


import QrCodeGenerator from '@/components/QrCodeGenerator.vue';
import {ref} from "vue";
import {ElLoading, ElMessage} from "element-plus";

const searchStore = defineStore('storeStore', {

  state: () => {
    return {
      searchObject: {
        no: 1,
        size: 30,
        sortField: "id",
        sortMethod: "desc",
        shop: '',
        name: '',
        shopState: null,
        phone: ''
      }
    }
  }
})

const title = ref("");
const store = ref({});
const showDialog = ref(false);
const qrUrl = ref("");
const importVisible = ref(false);
const configDialogVisible = ref(false)
const configData = ref([])

const showState = (row) => {
  if (row.storeStatus === "normal") {
    return "已上线";
  } else {
    return "已下线";
  }
};
const updateShopState = async (row) => {
  let params = {};
  params.id = row.id;
  params.storeStatus = row.storeStatus;
  await http.post("/store/update", params);
  await search();
}

const updateShopSort = async (row) => {
  let params = {};
  params.id = row.id;
  params.sortData = row.sortData;
  await http.post("/store/update", params);
  await search();
}

const {searchObject} = searchStore();

const clearSearch = () => {
  searchObject.shop = "";
  searchObject.name = "";
  searchObject.shopState = "";
  searchObject.phone = "";
}

const showStoreView = (row) => {
  title.value = `开卡码(${row.name})`
  store.value = row;
  showDialog.value = true;
  qrUrl.value = `http://wt.nbsaas.com/store/${row.id}`
}

const showPayView = (row) => {
  title.value = `付款码(${row.name})`
  store.value = row;
  showDialog.value = true;
  qrUrl.value = `http://wt.nbsaas.com/pay/${row.id}`

}

const closeDialog = () => {
  showDialog.value = false;

}

const exportToExcel = () => {
  // 将JSON数据转换为工作表
  const ws = XLSX.utils.json_to_sheet(pageData.value.data);

  // 创建一个新的工作簿
  const wb = XLSX.utils.book_new();

  // 将工作表添加到工作簿中
  XLSX.utils.book_append_sheet(wb, ws, 'Sheet1');

  // 生成Excel文件并下载
  XLSX.writeFile(wb, 'data.xlsx');

}


const exportToExcel1 = () => {
  // 将JSON数据转换为工作表
  // 定义表头
  let data = pageData.value.data;
  const headers = ['商家名称', '商家分类', '联系电话'];
  // 将表头和数据合并
  const ws_data = [headers, ...data.map(item => [item.name, item.catalogName, item.phone])];

  // 创建工作表
  const ws = XLSX.utils.aoa_to_sheet(ws_data);

  // 创建工作簿
  const wb = XLSX.utils.book_new();
  XLSX.utils.book_append_sheet(wb, ws, 'Sheet1');

  // 导出Excel文件
  XLSX.writeFile(wb, 'data.xlsx');

}


const exportToExcel2 = async () => {
  const workbook = new ExcelJS.Workbook();
  const worksheet = workbook.addWorksheet('Sheet1');

  // 模拟数据
  const data = pageData.value.data;

  // 添加列头
  worksheet.columns = [
    {header: '商家名称', key: 'name', width: 30},
    {header: '商家分类', key: 'storeCatalogName', width: 10},
    {header: '联系电话', key: 'phone', width: 20}
  ];

  // 添加行数据
  data.forEach(item => {
    worksheet.addRow(item);
  });

  // 生成Excel文件的Buffer
  const buffer = await workbook.xlsx.writeBuffer();

  // 使用file-saver保存文件
  saveAs(new Blob([buffer], {type: 'application/octet-stream'}), '商家列表.xlsx');

}

const importToExcel = () => {
  importVisible.value = true;

}

const handleBeforeUpload = (file) => {
  return false;
}
const handleChange = (file) => {
  const reader = new FileReader();
  reader.onload = (e) => {
    const data = new Uint8Array(e.target.result);
    const workbook = XLSX.read(data, {type: 'array'});

    // 读取第一个工作表
    const firstSheetName = workbook.SheetNames[0];
    const worksheet = workbook.Sheets[firstSheetName];

    // 转换为JSON
    const jsonData = XLSX.utils.sheet_to_json(worksheet, {header: 1});
    console.info(jsonData)
  };
  reader.readAsArrayBuffer(file.raw);
}

const closeImportDialog = () => {
  importVisible.value = false;
}

const showStoreVipCard = async (row) => {
  console.log(row);

  const loading = ElLoading.service({
    lock: true,
    text: '数据处理中',
    background: 'rgba(0, 0, 0, 0.7)',
  })
  let param = {};
  param.store = row.id;
  param.configKey = "config";

  let res = await http.post(`/storeVipCardConfig/config`, param);
  loading.close();
  if (res.code !== 200) {
    ElMessage.error(res.msg)
    return
  }
  configData.value = res.data;

  configDialogVisible.value = true;
}

const saveConfig = async (row) => {
  const loading = ElLoading.service({
    lock: true,
    text: '数据处理中',
    background: 'rgba(0, 0, 0, 0.7)',
  })

  let res = await http.post(`/storeVipCardConfig/update`, row);
  loading.close();
  if (res.code !== 200) {
    ElMessage.error(res.msg)
    return
  }

  ElMessage({
    message: '保存成功',
    type: 'success',
  })

}

const batchSave = async () => {


  const loading = ElLoading.service({
    lock: true,
    text: '数据处理中',
    background: 'rgba(0, 0, 0, 0.7)',
  })
  console.info(configData.value)
  for (let i = 0; i < configData.value.length; i++) {
    let row = configData.value[i];
    console.info(row)
    let res = await http.post(`/storeVipCardConfig/update`, row);
    if (res.code !== 200) {
      ElMessage.error(res.msg)
      return
    }
  }

  loading.close();
  ElMessage({
    message: '保存成功',
    type: 'success',
  })


}

const {pageData, sizeChange, pageChange, search, changeTableSort, loading} = usePage("/store/search", searchObject);
const {dialogVisible, deleteData, handleDelete} = useDelete("/store/delete", search);
const {showView, addView, editView} = useView();

</script>

<style scoped>
</style>

